package edu.upc.fib.lamsandroid.client.request.activity;

import com.google.gson.Gson;
import com.octo.android.robospice.request.SpiceRequest;
import edu.upc.fib.lamsandroid.client.LamsAndroidClientApplication;
import edu.upc.fib.lamsandroid.server.api.response.activity.GetByIdResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

public class GetActivityByIdRequest extends SpiceRequest<GetByIdResponse> {

    private Long id;

    private Gson gson;

    public GetActivityByIdRequest(Long id) {
        super(GetByIdResponse.class);

        this.id = id;
        gson = new Gson();
    }

    @Override
    public GetByIdResponse loadDataFromNetwork() throws Exception {

        LamsAndroidClientApplication app = LamsAndroidClientApplication.getInstance();
        String host = app.getPreferences().getString("host_preference", "");
        int port = Integer.parseInt(app.getPreferences().getString("port_preference", "0"));
        String context = app.getPreferences().getString("context_preference", "");

        HttpPost httppost = new HttpPost("http://" + host + ":" + port + "/" + context + "/activity/getById");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("id", String.valueOf(id)));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = app.doPost(httppost);

        String json = IOUtils.toString(httpResponse.getEntity().getContent());

        return gson.fromJson(json, GetByIdResponse.class);
    }
}
